<template>
	<view class="inspect-sensor">
		<view class="top">
			<view>{{$t('inspection.taskExecute.bluetoothStatus')}}：
				<text v-if="!connectedDevice" class="did">{{$t('inspection.taskExecute.notConnected')}}</text>
				<text v-else class="did">{{$t('inspection.taskExecute.connected')}} {{ connectedDevice.deviceId }}</text>
			</view>
			<button v-if="connectedDevice" type="primary" size="mini" plain="true" @click="closeConnect">{{$t('inspection.taskExecute.disconnect')}}</button>
		</view>
		<view v-if="available" class="content">
			<view class="able" v-for="(item, index) in sensorList" :key="index" @click="connect(item)" >
				<view class="title">{{ item.name }}</view>
				<view class="desc">{{$t('common.field.address')}}：{{ item.deviceId }}</view>
				<view class="desc">RSSI：{{ item.rssi }}</view>
			</view>
		</view>
		<view v-else class="unable" @click="init">
			<text>{{ unableText }}</text>
		</view>
	</view>
</template>

<script>
	import { notice, utilities } from '@/utils/common.js'
	import { inspect as util } from '@/utils/business/common.js'
	
    export default {
        data() {
            return {
				available: true,
				unableText: this.$t('inspection.message.bluetoothClosed'),
				sensorList: [],
				connectedDevice: '',
				beginCollectTime: '',
				endCollectTime: ''
            }
        },
		onLoad() {
			this.connectedDevice = uni.getStorageSync("bindSensor")
			this.init()
		},
        methods: {
			init() {
				this.sensorList = uni.getStorageSync("sensorList")
				this.openBle()
			},
			openBle(){
				let _this = this;
			    uni.openBluetoothAdapter({
			        success(data) {
			            _this.available = true
						_this.searchDevice()
			        },
			        fail: (err) => {
						_this.available = false
			        }
			    })
			},
			searchDevice(){
				let _this = this;
				
				// 记录日志
				util.logCollectStatus({
					itemType: 'blue_list',
					beginCollectTime: utilities.getNowDateTime()
				})
				
			    uni.startBluetoothDevicesDiscovery({
			        success(data) {
			            _this.onBluetoothDeviceFound();
			        },
			        fail(err) {
			            console.log("fail",err);
			        }
			    })
			},
			onBluetoothDeviceFound(){
			    let _this = this;
				uni.showLoading({
					title: _this.$t('inspection.message.searching'),
					mask: true
				})
				
			    uni.onBluetoothDeviceFound(function(res){
			        let devices = res.devices;
			        for (var i = 0; i < devices.length; i++) {
						const device = devices[i];
						// 增加传感器名称过滤
						if(_this.sensorList.findIndex(r=>r.deviceId === device.deviceId) === -1 && device.name.indexOf('BT') !== -1) {
							_this.sensorList.push({
								name: device.name || "Unknown Device",
								deviceId: device.deviceId,
								rssi: device.RSSI
							})
						}
						if(_this.sensorList.length > 0) {
							setTimeout(() => {
								uni.hideLoading()
							}, 2000)
						}
			        }
			    })
			},
			connect(device) {
				// TODO 校验数据字典是否配置该deviceId
				// notice.toast('该传感器未被允许连接该设备,请联系管理员')
				
				// 校验当前是否已连接传感器
				let current = uni.getStorageSync("bindSensor")
				if(current.deviceId == device.deviceId) {
					notice.toast(this.$t('inspection.message.sensorConnected'))
					return
				} else {
					this.closeConnect('auto')
				}
				
				uni.showLoading({
				    title: this.$t('inspection.message.connecting')
				});
				this.beginCollectTime = utilities.getNowDateTime()
				
				let _this = this;
				uni.createBLEConnection({
				    deviceId: device.deviceId,
				    success(res) {
						uni.hideLoading()
						notice.toast(_this.$t('inspection.message.connectionSuccess'))
						_this.connectedDevice = device
						uni.setStorageSync("bindSensor", _this.connectedDevice)
						
						const eventChannel = _this.getOpenerEventChannel();
						eventChannel.emit('bindSensor', _this.connectedDevice);
						uni.navigateBack();
						
						_this.stopBluetoothDevicesDiscovery()
						
						// 记录日志
						util.logCollectStatus({
							eqCode: _this.connectedDevice.deviceId,
							itemType: 'blue_link',
							collectState: 10,
							blueLinkResult: _this.sensorList.findIndex(r => r.deviceId === device.deviceId) === -1 ? 10 : 20,
							beginCollectTime: _this.beginCollectTime,
							endCollectTime: utilities.getNowDateTime()
						})
				    },
				    fail(err) {
						console.log(err)
						notice.toast(_this.$t('inspection.message.connectionFail'))
						
						// 记录日志
						util.logCollectStatus({
							eqCode: device.deviceId,
							itemType: 'blue_link',
							collectState: 20,
							blueLinkResult: _this.sensorList.findIndex(r => r.deviceId === device.deviceId) === -1 ? 10 : 20,
							beginCollectTime: _this.beginCollectTime,
							endCollectTime: utilities.getNowDateTime()
						})
						
						// 重新搜索
						_this.searchDevice()
				    }
				})  
			},
			// 停止搜寻蓝牙设备
			stopBluetoothDevicesDiscovery(){ 
				uni.stopBluetoothDevicesDiscovery({ 
					success(res) {
						console.log('停止搜索蓝牙设备:' + res.errMsg); 
					},
					fail(err) {
						console.log('停止搜索蓝牙设备失败，错误码：' + err.errCode);
					}
				});
			},
			// 断开连接
			closeConnect() {
				let _this = this;
				uni.closeBLEConnection({
					deviceId: _this.connectedDevice.deviceId,
					success(res) {
						if(type != 'auto') {
							notice.toast(_this.$t('inspection.message.connectionDropped'))
						}
						
						// 记录日志
						util.logCollectStatus({
							eqCode: _this.connectedDevice.deviceId,
							itemType: 'blue_close'
						})
						
						_this.connectedDevice = ''
						uni.removeStorageSync('bindSensor')
						
						var pages = getCurrentPages();
						var prevPage = pages[pages.length - 2]; //上一个页面
						prevPage.$vm.relieveBind();
					}
				})
			}
        }
    }
</script>

<style lang="scss" scoped>
	.top {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 8px;
		border-bottom: 1px solid #ddd;
		position: fixed;
		width: 100%;
		height: 50px;
		background-color: #F1F1F1;
		font-size: 14px;

		.did {
			color: $uni-color-success;
		}
		
		uni-button {
			border-radius: 100px;
			margin-right: 10px;
			background-color: rgba(0,0,0,0);
		}
	}
	
	.content {
		padding-top: 50px;
		
		.able {
			padding: 10px;
			border-bottom: 1px solid #ddd;
			
			.title {
				font-size: 16px;
				color: #000;
				margin-bottom: 5px;
			}
			
			.desc {
				color: #666;
			}
		}
	}
	
	.unable {
		font-size: 16px;
		text-align: center;
		padding-top: 100px;
		background-color: #999;
		/* #ifdef APP-PLUS */
		height: 100vh;
		/* #endif*/
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif*/
	}
</style>
